package com.yungu.swift.api.route.v1.passenger;

import com.alibaba.dubbo.config.annotation.Reference;
import com.yungu.swift.api.base.BaseApi;
import com.yungu.swift.api.utils.RandomUtil;
import com.yungu.swift.assets.driver.service.CarModelService;
import com.yungu.swift.assets.driver.service.DriverService;
import com.yungu.swift.assets.passenger.model.dto.PassengerDto;
import com.yungu.swift.assets.passenger.service.PassengerService;
import com.yungu.swift.base.ResponseData;
import com.yungu.swift.common.model.dto.CommonArticleDto;
import com.yungu.swift.common.model.dto.CommonErrorMessageDto;
import com.yungu.swift.common.model.dto.CommonTagDto;
import com.yungu.swift.common.model.vo.AppVersionVo;
import com.yungu.swift.common.service.*;
import com.yungu.swift.constants.CommonConstant;
import com.yungu.swift.constants.MagicConstant;
import com.yungu.swift.lbs.model.DriverPoint;
import com.yungu.swift.lbs.service.LocationService;
import com.yungu.swift.system.marketing.model.dto.MarketingActivityDto;
import com.yungu.swift.system.marketing.service.MarketingActivityService;
import com.yungu.swift.system.sys.model.dto.SysAirportDto;
import com.yungu.swift.system.sys.model.dto.SysAreaDto;
import com.yungu.swift.system.sys.model.dto.SysCityDto;
import com.yungu.swift.system.sys.model.dto.SysCountryDto;
import com.yungu.swift.system.sys.model.vo.BusinessDetailVo;
import com.yungu.swift.system.sys.service.*;
import com.yungu.swift.utils.MapUtils;
import com.yungu.swift.utils.StringUtils;
import com.yungu.swift.utils.ValidateUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.*;
import java.util.stream.Collectors;


/**
 * @author Zerrion
 * @description
 * @date 2016/12/6. <br>
 */
@Slf4j
@Controller
@RequestMapping("/api/v1/passenger")
@Api(value = "【乘客】【通用】通用模块接口", tags = "获取标签，帮助文档和开通业务的相关操作")
public class CommonApi extends BaseApi {
    @Reference
    private CommonTagService commonTagService;
    @Reference
    private CommonArticleService commonArticleService;
    @Reference
    private LocationService locationService;
    @Reference
    private CommonVersionService commonVersionService;
    @Reference
    private SysCityService sysCityService;
    @Reference
    private SysBusinessCityService sysBusinessCityService;
    @Reference
    private DriverService driverService;
    @Reference
    private MarketingActivityService marketingActivityService;
    @Reference
    private SysCountryService sysCountryService;
    @Reference
    private PassengerService passengerService;
    @Reference
    private CommonErrorMessageService commonErrorMessageService;
    @Reference
    private SysAreaService sysAreaService;
    @Reference
    private SysAirportService sysAirportService;
    @Reference
    private CarModelService carModelService;
    @Reference
    private CommonSmsService commonSmsService;


    @RequestMapping(value = {"/tag/evaluate"}, method = {RequestMethod.POST, RequestMethod.GET})
    @ResponseBody
    @ApiOperation(value = "获取评价列表", response = ResponseData.class, notes = "list")
    public ResponseData<List<CommonTagDto>> listOfEvaluate(
            @ApiParam(name = "appid", value = "APP标识", required = true) @RequestParam String appid) {
        Map<String, Object> map = MapUtils.build(4);
        //乘客
        map.put("identity", CommonConstant.PASSENGER);
        map.put("tagType", CommonConstant.TAG_TYPE_EVALUATE);
        map.put("tagStatus", MagicConstant.INT_ONE);
        map.put("appid", appid);
        List<CommonTagDto> commonTagDtoList = commonTagService.list(map).getData();
        //查询无数据，返回空数组
        if (commonTagDtoList == null || commonTagDtoList.size() == 0) {
            commonTagDtoList = new ArrayList<>();
        }
        return ResponseData.buildSuccessResponse("查询数据成功", commonTagDtoList);
    }

    @RequestMapping(value = {"/tag/complain"}, method = {RequestMethod.POST, RequestMethod.GET})
    @ResponseBody
    @ApiOperation(value = "获取投诉列表", response = ResponseData.class, notes = "list")
    public ResponseData<List<CommonTagDto>> listOfComplain(
            @ApiParam(name = "appid", value = "APP标识", required = true) @RequestParam String appid) {
        Map<String, Object> map = MapUtils.build(3);
        map.put("tagType", CommonConstant.TAG_TYPE_COMPLAIN);
        map.put("tagStatus", MagicConstant.INT_ONE);
        map.put("identity", CommonConstant.PASSENGER);
        map.put("appid", appid);
        return commonTagService.list(map);
    }

    @RequestMapping(value = {"/tag/takemsg"}, method = {RequestMethod.POST, RequestMethod.GET})
    @ResponseBody
    @ApiOperation(value = "获取捎话列表", response = ResponseData.class, notes = "list")
    public ResponseData<List<CommonTagDto>> listOfTakeMsg(
            @ApiParam(name = "appid", value = "APP标识", required = true) @RequestParam String appid,
            @ApiParam(name = "businessType", value = "业务类型", required = false) @RequestParam(required = false) Integer businessType) {

        Map<String, Object> map = MapUtils.build(3);
        map.put("tagType", CommonConstant.TAG_TYPE_SEND_ORAL);
        map.put("tagStatus", MagicConstant.INT_ONE);
        map.put("identity", CommonConstant.PASSENGER);
        map.put("appid", appid);
        if (businessType != null) {
            map.put("businessType", businessType);
        }
        return commonTagService.list(map);
    }

    @RequestMapping(value = {"/tag/problem"}, method = {RequestMethod.POST, RequestMethod.GET})
    @ResponseBody
    @ApiOperation(value = "获取常见问题", response = ResponseData.class, notes = "list")
    public ResponseData<List<CommonArticleDto>> listOfProblem(
            @ApiParam(name = "appid", value = "APP标识", required = true) @RequestParam String appid) {
        Map<String, Object> map = MapUtils.build(4);
        map.put("appid", appid);
        map.put("articleType", CommonConstant.PASSENGER);
        ResponseData<List<CommonArticleDto>> responseData = commonArticleService.list(map);
        if (responseData.isSuccess() && CollectionUtils.isNotEmpty(responseData.getData())) {
            List<CommonArticleDto> data = responseData.getData();
            for (CommonArticleDto articleDto : data) {
                articleDto.setArticleSimpleContent(null);
                articleDto.setArticleContent(null);
            }
        }
        return responseData;
    }

    @RequestMapping(value = {"/tag/cancelMsg"}, method = {RequestMethod.POST, RequestMethod.GET})
    @ResponseBody
    @ApiOperation(value = "获取取消原因列表", response = ResponseData.class, notes = "list")
    public ResponseData<List<CommonTagDto>> listOfCancelMsg(
            @ApiParam(name = "appid", value = "APP标识", required = true) @RequestParam String appid) {
        Map<String, Object> map = MapUtils.build(3);
        map.put("tagType", CommonConstant.TAG_TYPE_CANCEL);
        map.put("tagStatus", MagicConstant.INT_ONE);
        map.put("identity", CommonConstant.PASSENGER);
        map.put("appid", appid);
        return commonTagService.list(map);
    }

    @RequestMapping(value = {"/sysBusinessCity/list"}, method = {RequestMethod.POST, RequestMethod.GET})
    @ResponseBody
    @ApiOperation(value = "获取开通城市业务二维列表", response = ResponseData.class, notes = "list")
    public ResponseData<List<BusinessDetailVo>> openList(
            @ApiParam(name = "appid", value = "APP标识", required = true) @RequestParam String appid) {
        return sysBusinessCityService.getBusinessDetail(MapUtils.build("organizationUuid", appid));
    }

    @RequestMapping(value = {"/map/around"}, method = {RequestMethod.POST, RequestMethod.GET})
    @ResponseBody
    @ApiOperation(value = "获取周围司机", response = ResponseData.class, notes = "list")
    public ResponseData<List<DriverPoint>> map(
            @ApiParam(name = "appid", value = "APP标识", required = true) @RequestParam String appid,
            @ApiParam(name = "type", value = "业务类型（1.出租车，2专车 3跨城拼车 4快车）", required = true) @RequestParam Integer type,
            @ApiParam(name = "lng", value = "经度", required = true) @RequestParam Double lng,
            @ApiParam(name = "lat", value = "纬度", required = true) @RequestParam Double lat) {

        List<DriverPoint> driverPoints = locationService.geoNearOnline(type, lng, lat, appid, 8000, 100).getData();
        if (CollectionUtils.isNotEmpty(driverPoints)) {
            List<String> driverUuids = driverPoints.stream().map(driverPoint -> driverPoint.getDriverUuid()).distinct()
                    .collect(Collectors.toList());
            //过滤上班状态司机
            List<String> workDriverUuids = driverService.filterWorkUuid(driverUuids).getData();
            if (CollectionUtils.isNotEmpty(workDriverUuids)) {
                driverPoints = driverPoints.stream().filter(driverPoint ->
                        workDriverUuids.contains(driverPoint.getDriverUuid())).collect(Collectors.toList());
            }
        }
        return ResponseData.buildSuccessResponse("获取成功", driverPoints);
    }

    @RequestMapping(value = {"/version/check"}, method = {RequestMethod.POST, RequestMethod.GET})
    @ResponseBody
    @ApiOperation(value = "版本更新", response = ResponseData.class)
    public ResponseData<AppVersionVo> check(
            @ApiParam(name = "appid", value = "APP标识", required = true) @RequestParam String appid,
            @ApiParam(name = "platform", value = "平台（android/ios）", required = true) @RequestParam String platform,
            @ApiParam(name = "versionNo", value = " 版本No", required = true) @RequestParam String versionNo) {

        if (StringUtils.isEmpty(platform) || StringUtils.isEmpty(versionNo)) {
            return ResponseData.buildErrorResponse(ResponseData.ERROR_CODE, "参数不能为空");
        }
        return commonVersionService.checkVersion(platform, versionNo, CommonConstant.PASSENGER, appid);
    }

//    @RequestMapping(value = {"/identifyCode/send"}, method = {RequestMethod.POST, RequestMethod.GET})
//    @ResponseBody
//    @ApiOperation(value = "发送验证码", response = ResponseData.class, notes = "发送短信验证码接口")
//    public ResponseData<Boolean> send(
//            @ApiParam(name = "appid", value = "APP标识", required = true) @RequestParam(value = "appid") String appid,
//            @ApiParam(name = "mobile", value = "手机号码", required = true) @RequestParam(value = "mobile") String mobile,
//            @ApiParam(name = "countryMobileCode", value = "国家手机号码前缀", required = false) @RequestParam(value = "countryMobileCode", required = false) String countryMobileCode
//    ) {
//        String decryptMobile = RandomUtil.randomDecrypt(mobile);
//        if (!ValidateUtils.validateMobile(decryptMobile)) {
//            return ResponseData.buildErrorResponse(ResponseData.ERROR_CODE, "手机号码格式错误");
//        }
//        return commonSmsService.sendIdentify(decryptMobile, appid);
//    }

    @RequestMapping(value = {"/identifyCode/send"}, method = {RequestMethod.POST, RequestMethod.GET})
    @ResponseBody
    @ApiOperation(value = "发送验证码", response = ResponseData.class, notes = "发送短信验证码接口")
    public ResponseData<Boolean> send(
            @ApiParam(name = "appid", value = "APP标识", required = true) @RequestParam(value = "appid") String appid,
            @ApiParam(name = "mobile", value = "手机号码", required = true) @RequestParam(value = "mobile") String mobile,
            @ApiParam(name = "countryMobileCode", value = "国家手机号码前缀", required = false) @RequestParam(value = "countryMobileCode", required = false) String countryMobileCode
    ) {
        String decryptMobile = RandomUtil.randomDecrypt(mobile);
        if (!ValidateUtils.validateMobile(decryptMobile)) {
            return ResponseData.buildErrorResponse(ResponseData.ERROR_CODE, "手机号码格式错误");
        }
        return commonSmsService.sendAliIdentify(decryptMobile, appid);
    }

    @RequestMapping(value = {"/city/find"}, method = {RequestMethod.POST, RequestMethod.GET})
    @ResponseBody
    @ApiOperation(value = "获取指定城市信息接口", notes = "", response = ResponseData.class)
    public ResponseData<SysCityDto> findOne(
            @ApiParam(name = "sign", value = "签名") @RequestParam(value = "sign", required = true) String sign,
            @ApiParam(name = "appid", value = "APP标识") @RequestParam(value = "appid", required = true) String appid,
            @ApiParam(name = "noncestr", value = "随机数") @RequestParam(value = "noncestr", required = true) String noncestr,
            @ApiParam(name = "name", value = "城市", required = true) @RequestParam(value = "name", required = true) String name,
            HttpServletRequest request) {

        if (name == null) {
            return ResponseData.buildErrorResponse(ResponseData.ERROR_CODE, "参数不能空");
        }
        if (appid == null) {
            return ResponseData.buildErrorResponse(ResponseData.ERROR_CODE, "参数不能空");
        }

        Map<String, Object> map = MapUtils.build(1);
        map.put("appid", appid);
        map.put("name", name);
        return sysCityService.get(map);
    }


    @RequestMapping(value = {"/marketing/activity/list"}, method = {RequestMethod.POST, RequestMethod.GET})
    @ResponseBody
    @ApiOperation(value = "获取活动信息", notes = "获取活动信息", response = ResponseData.class)
    public ResponseData<List<MarketingActivityDto>> listActivity(
            @ApiParam(name = "appid", value = "APP标识", required = true) @RequestParam(value = "appid") String appid,
            @ApiParam(name = "adCode", value = "城市区划编码") @RequestParam(value = "adCode", required = false) String adCode,
            @ApiParam(name = "businessType", value = "业务类型") @RequestParam(value = "businessType", required = false) Integer businessType,
            @ApiParam(name = "showType", value = "展示类型") @RequestParam(value = "showType", required = false) Integer showType,
            @ApiParam(name = "token", value = "乘客token") @RequestParam(value = "token", required = false) String token) {

        Map<String, Object> map = MapUtils.build();
        map.put("appid", appid);
        if (StringUtils.isNotEmpty(adCode)) {
            String passengerCityUuid = "";
            //不为空的话先转成cityID,这边要获取到area的UUID和
            Map searchMap = MapUtils.build(1);
            searchMap.put("areaID", adCode);
            Object object = sysAreaService.get(searchMap).getData();
            if (object != null) {
                SysAreaDto sysAreaDto = (SysAreaDto) object;
                String areaUuid = sysAreaDto.getUuid();
                if (businessType!= null && businessType != CommonConstant.BUSINESS_TYPE_POOL) {
                    map.put("paramAreaUuid", areaUuid);
                    //如果areaUuid 在 city表查的到的话，说明是作为区县管理
                    Map searchCityMap = MapUtils.build(1);
                    searchCityMap.put("uuid", areaUuid);
                    if (sysCityService.get(searchCityMap).getData() != null) {
                        passengerCityUuid = areaUuid;
                    }
                } else {
                    map.put("paramAreaUuid", areaUuid);
                    //跨城情况下 需要找到区域的上一级城市
                    adCode = sysAreaDto.getFather();
                }
            }
            if (businessType!= null && businessType != CommonConstant.BUSINESS_TYPE_POOL) {
                String cityUuid = sysCityService.getCityUuidByAdCode(adCode).getData();
                if (StringUtils.isNotEmpty(cityUuid) && StringUtils.isEmpty(passengerCityUuid)) {
                    map.put("paramCityUuid", cityUuid);
                    passengerCityUuid = cityUuid;
                }
            } else {
                SysCityDto sysCityDto = sysCityService.get(MapUtils.build("cityID", adCode)).getData();
                if (sysCityDto != null) {
                    map.put("paramCityUuid", sysCityDto.getUuid());
                }
            }

            map.put("adCode", adCode);
            //如果token不为空，获取乘客信息，并且更新乘客所在区域
            if (StringUtils.isNotEmpty(token)) {
                Map<String, String> pasengerMap = passengerService.getPassengerCachedByToken(token).getData();
                if (pasengerMap != null) {
                    PassengerDto eidtDto = new PassengerDto();
                    eidtDto.setUuid(pasengerMap.get("uuid"));
                    eidtDto.setCurrentAdCode(adCode);
                    eidtDto.setCityUuid(passengerCityUuid);
                    passengerService.edit(eidtDto);
                }
            }
        } else {
            //为空也传，为空就取全国发放的
            map.put("adCodeNull", 1);
        }
        if (businessType != null) {
            map.put("businessType", businessType);
        }
        if (showType != null) {
            map.put("showType", showType);
        }
        return marketingActivityService.getActivities(map);
    }

    @RequestMapping(value = {"/marketing/activity/countActivity"}, method = {RequestMethod.POST, RequestMethod.GET})
    @ResponseBody
    @ApiOperation(value = "增加活动点击量", notes = "增加活动点击量", response = ResponseData.class)
    public ResponseData<Boolean> countActivity(


            @ApiParam(name = "appid", value = "APP标识", required = true) @RequestParam(value = "appid") String appid,
            @ApiParam(name = "activityUuid", value = "活动的uuid", required = true) @RequestParam(value = "activityUuid") String activityUuid,
            HttpServletRequest request) {

        return marketingActivityService.updateCilckCount(activityUuid);
    }

    @RequestMapping(value = {"/system/getAirport"}, method = {RequestMethod.POST, RequestMethod.GET})
    @ResponseBody
    @ApiOperation(value = "获取城市机场列表", notes = "获取城市机场列表", response = ResponseData.class)
    public ResponseData<List<SysAirportDto>> getSysAirport(
            @ApiParam(name = "appid", value = "APP标识", required = true) @RequestParam String appid,

            @ApiParam(name = "cityName", value = "城市名", required = true) @RequestParam String cityName) {
        Object object = sysAirportService.getAirportByCityName(MapUtils.build("city", cityName)).getData();
        if (object != null) {
            List<SysAirportDto> list = (List<SysAirportDto>) object;
            return ResponseData.buildSuccessResponse("获取机场信息成功", list);

        }
        return ResponseData.buildErrorResponse(ResponseData.ERROR_CODE, "未获取到机场信息");
    }

    @RequestMapping(value = {"/country/getCountryList"}, method = {RequestMethod.POST, RequestMethod.GET})
    @ResponseBody
    @ApiOperation(value = "获取国家列表", notes = "获取国家列表", response = ResponseData.class)
    public ResponseData<List<SysCountryDto>> getCountryList(
            @ApiParam(name = "appid", value = "APP标识", required = true) @RequestParam String appid) {
        return sysCountryService.list(null);
    }

    @RequestMapping(value = {"/token/uploadErrorMsg"}, method = {RequestMethod.POST, RequestMethod.GET})
    @ResponseBody
    @ApiOperation(value = "上传错误日志", response = ResponseData.class, notes = "上传错误日志")
    public ResponseData<Boolean> uploadErrorMsg(

            @ApiParam(name = "appid", value = "APP标识", required = true) @RequestParam String appid,

            @ApiParam(name = "token", value = "token", required = true) @RequestParam("token") String token,
            @ApiParam(name = "errorModule", value = "错误模块", required = true) @RequestParam String errorModule,
            @ApiParam(name = "errorType", value = "错误类型", required = true) @RequestParam String errorType,
            @ApiParam(name = "errorMsg", value = "错误信息", required = true) @RequestParam String errorMsg,
            @ApiParam(name = "terminalId", value = "手机Id", required = false) @RequestParam(required = false) String terminalId,
            @ApiParam(name = "terminalVersion", value = "手机版本", required = false) @RequestParam(required = false) String terminalVersion,
            HttpServletRequest request) {
        CommonErrorMessageDto commonErrorMessageDto = new CommonErrorMessageDto();
        commonErrorMessageDto.setUuid(StringUtils.buildUUID());
        commonErrorMessageDto.setCreateOn(new Date());
        commonErrorMessageDto.setCreateBy(getUserUid(request));
        commonErrorMessageDto.setUploadFrom(CommonErrorMessageDto.UPLOAD_FROM_PASSENGER);
        commonErrorMessageDto.setErrorModule(errorModule);
        commonErrorMessageDto.setErrorType(errorType);
        commonErrorMessageDto.setErrorMsg(errorMsg);
        commonErrorMessageDto.setTerminalId(terminalId);
        commonErrorMessageDto.setTerminalVersion(terminalVersion);
        return commonErrorMessageService.add(commonErrorMessageDto);
    }

    @RequestMapping(value = {"/carLevel/getMaxSeats"}, method = {RequestMethod.POST, RequestMethod.GET})
    @ResponseBody
    @ApiOperation(value = "获取最大座位数", response = ResponseData.class, notes = "获取最大座位数")
    public ResponseData<Map<String, Object>> getMaxSeats(

            @ApiParam(name = "appid", value = "APP标识", required = true) @RequestParam String appid,
            @ApiParam(name = "businessType", value = "业务类型", required = true) @RequestParam Integer businessType) {
        Map<String, Object> params = new HashMap<>(2);
        params.put("businessType", businessType);
        Integer maxSeats = carModelService.getMaxSeats(params).getData();
        return ResponseData.buildSuccessResponse(MapUtils.build("maxSeats", maxSeats));

    }
}
